package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.AbsButton;

final class AbsButtonCheckedStateChangedObservable extends InitialValueObservable<Boolean> {
    private final AbsButton view;

    AbsButtonCheckedStateChangedObservable(AbsButton view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super Boolean> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setCheckedStateChangedListener(listener);
    }

    @Override
    protected Boolean getInitialValue() {
        return view.isChecked();
    }

    static final class Listener extends MainThreadDisposable implements AbsButton.CheckedStateChangedListener {
        private final AbsButton view;
        private final Observer<? super Boolean> observer;

        Listener(AbsButton view, Observer<? super Boolean> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setCheckedStateChangedListener(null);
        }

        @Override
        public void onCheckedChanged(AbsButton absButton, boolean b) {
            if (!isDisposed()) {
                observer.onNext(b);
            }
        }
    }
}
